package model

import (
	"time"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

type User struct {
	ID        string    `json:"id"`
	UserName  string    `json:"user_name"`
	Email     string    `json:"email"`
	Password  string    `json:"password"`
	RoleID    string    `json:"role_id"`
	RoleName  string    `json:"role_name"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

func CreateUser(db *gorm.DB, u *User) error {
	if u.ID == "" {
		u.ID = uuid.NewString()
	}
	return db.Create(u).Error
}

func DeleteUser(db *gorm.DB, id string) error {
	return db.Delete(&User{}, "id = ?", id).Error
}

func UpdateUser(db *gorm.DB, u *User) error {
	return db.Model(&User{ID: u.ID}).Updates(*u).Error
}

func ListUser(db *gorm.DB, filters map[string]interface{}) ([]User, error) {
	uu := []User{}
	err := db.Where(filters).Find(&uu).Error
	return uu, err
}

func FindUserByName(db *gorm.DB, name string) (User, error) {
	u := User{}
	err := db.Where("user_name = ?", name).First(&u).Error
	return u, err
}

func FindUserByNamePass(db *gorm.DB, username, password string) (*User, error) {
	u := User{}
	err := db.Where("user_name = ? AND password = ?", username, password).First(&u).Error
	return &u, err
}

func FindUser(db *gorm.DB, id string) (User, error) {
	u := User{}
	err := db.Where("id = ?", id).First(&u).Error
	return u, err
}
